<template>
	<view class="countwrap">
		<view class="count-down">
			<text class="box">{{d}}天{{h}}小时{{m}}分钟</text>
			<!-- <text class="tag">天</text>
			<text class="box">{{h}}</text>
			<text class="tag">小时</text>
			<text class="box">{{m}}</text>
			<text class="tag">分钟</text> -->
			<!-- <text class="box">{{s}}</text>
			<text class="tag">秒</text> -->
		</view>
	</view>
</template>

<script>
	export default {
		name: 'benCountdown',
		props: {
			leftSeconds: {
				type: [String, Number],
				default: 0
			}
		},
		data() {
			return {
				seconds:0,
				timer: null,
				d: '00',
				h: '00',
				m: '00',
				s: '00'
			};
		},
		created() {
			clearInterval(this.timer);
			this.seconds = this.leftSeconds
			this.init();
		},
		beforeDestroy() {
			clearInterval(this.timer);
		},
		methods: {
			// 初始化函数
			init() {
				this.countDown();
				this.timer = setInterval(() => {
					this.seconds--;
					if (this.seconds < 0) {
						this.over();
						return;
					}
					this.countDown();
				}, 1000);
			},
			countDown() {
				let seconds = this.seconds;
				let [day, hour, minute, second] = [0, 0, 0, 0];
				if (seconds > 0) {
					day = Math.floor(seconds / 60 / 60 / 24);
					hour = Math.floor(seconds / 60 / 60 % 24);
					minute = Math.floor(seconds / 60 % 60);
					second = Math.floor(seconds % 60);
				} else {
					this.over();
				}
				if (day < 10) {
					day = '0' + day;
				}
				if (hour < 10) {
					hour = '0' + hour;
				}
				if (minute < 10) {
					minute = '0' + minute;
				}
				if (second < 10) {
					second = '0' + second;
				}
				this.h = hour;
				this.m = minute;
				this.s = second;
				this.d = day
			},
			// 倒计时结束触发函数
			over() {
				clearInterval(this.timer);
				setTimeout(() => {
					this.init();
				}, 1000);
			},
			refresh() {
				this.timer && clearInterval(this.timer);
				this.timer = null;
				this.init();
			}
		}
	}
</script>

<style lang="scss" scoped>
	.countwrap {
		height: 36rpx;
		border-radius: 6rpx;
		line-height: 32rpx;
		display: flex;
		.count-down {
			font-size: 28rpx;
			color: $theme;
		}
	}

	.tag {
		margin-right: 6rpx;
	}
</style>
